package com.xiaogao.serviceEdu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import com.xiaogao.serviceEdu.client.OSSClient;
import com.xiaogao.serviceEdu.entity.EduCourse;
import com.xiaogao.serviceEdu.entity.EduCourseDescription;
import com.xiaogao.serviceEdu.entity.vo.CourseInfoVO;
import com.xiaogao.serviceEdu.entity.vo.CoursePublishVo;
import com.xiaogao.serviceEdu.entity.vo.CourseQuery;
import com.xiaogao.serviceEdu.entity.vo.CourseWebVo;
import com.xiaogao.serviceEdu.mapper.EduCourseMapper;
import com.xiaogao.serviceEdu.service.EduChapterService;
import com.xiaogao.serviceEdu.service.EduCourseDescriptionService;
import com.xiaogao.serviceEdu.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaogao.serviceEdu.service.EduVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 小高
 * @since 2021-06-08
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    // 课程简介注入
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;
    @Autowired
    private EduVideoService videoService;
    @Autowired
    private EduChapterService chapterService;

    @Resource
    private OSSClient ossClient;

    // 保存课程和课程详情信息
    @Override
    public String saveCourseInfo(CourseInfoVO courseInfoVO) {
        // 1、向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        // 先存为草稿
        eduCourse.setStatus(EduCourse.COURSE_DRAFT);
        // 将CourseInfoVO对象转换为EduCourse对象
        BeanUtils.copyProperties(courseInfoVO,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert <= 0) {
            // 添加失败
            throw new XiaoGaoException(20001,"添加课程信息失败");
        }

        // 获取添加后的课程id
        String cid = eduCourse.getId();

        // 2、向课程简介表体添加课程简介
        EduCourseDescription courseDescription = new EduCourseDescription();
//        BeanUtils.copyProperties(courseInfoVO,courseDescription); // 由于值较少，直接用getset方法
        courseDescription.setDescription(courseInfoVO.getDescription());
        // 设置课程id与课程描述id保持一致
        courseDescription.setId(cid);
        boolean result = courseDescriptionService.save(courseDescription);
        if (!result){
            throw new XiaoGaoException(20001,"添加课程简介失败");
        }

        return cid;
    }

    // 根据id查询课程信息
    @Override
    public CourseInfoVO getCourseInfoVoById(String id) {
        EduCourse eduCourse = this.getById(id);
        if (eduCourse == null){
            throw new XiaoGaoException(20001,"数据不存在");
        }
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        BeanUtils.copyProperties(eduCourse,courseInfoVO);

        EduCourseDescription courseDescription = courseDescriptionService.getById(id);
        if (eduCourse != null){
            courseInfoVO.setDescription(courseDescription.getDescription());
        }

        return courseInfoVO;
    }

    // 根据id修改课程基本信息
    @Override
    public String updateCourseInfoById(CourseInfoVO courseInfoVO) {
        // 保存课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO,eduCourse);
        boolean flagCourse = this.updateById(eduCourse);
        if (!flagCourse){
            throw new XiaoGaoException(20001,"课程信息保存失败");
        }
        String cid = courseInfoVO.getId();
        // 保存课程简介信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVO.getDescription());
        courseDescription.setId(cid);
        boolean flagDes = courseDescriptionService.updateById(courseDescription);
        if (!flagDes){
            throw new XiaoGaoException(20001,"课程简介信息保存失败");
        }
        return cid;
    }

    // 根据课程id多表查询最终发布信息确认
    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return baseMapper.selectCoursePublishVoById(id);
    }

    // 根据id发布课程（修改课程表状态）
    @Override
    public boolean publishCourseById(String id) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(id);
        eduCourse.setStatus(EduCourse.COURSE_NORMAL);   // 改为终稿

        if (!this.updateById(eduCourse)){
            throw new XiaoGaoException(20001,"发布课程失败！");
        }else{
            return true;
        }
    }

    // 条件分页查询课程信息列表
    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        if (courseQuery == null){
            baseMapper.selectPage(pageParam,wrapper);
            return ;// 结束方法
        }

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)){
            wrapper.like("title",title);
        }
        if (!StringUtils.isEmpty(teacherId)){
            wrapper.eq("teacher_id",teacherId);
        }
        if (!StringUtils.isEmpty(subjectParentId)){
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectParentId)){
            wrapper.ge("subject_id",subjectId);
        }
        baseMapper.selectPage(pageParam,wrapper);

    }

    // 根据ID删除课程
    @Override
    public boolean removeCourseById(String id) {
        // 根据id删除所有视频
        videoService.removeCourseById(id);
        // 根据id删除所有章节
        chapterService.removeCourseById(id);
        // 根据id删除对应简介
        courseDescriptionService.removeCourseById(id);
        
        // 根据id删除对应封面 TODO
        // 获取头像路径
//        String cover = baseMapper.selectById(id).getCover();
//        String coverName = URLEncoder.encode(cover);
//        System.out.println(coverName);
//        ossClient.removeOssFile(coverName);


        Integer count = baseMapper.deleteById(id);
        if (count == 0){
            throw new XiaoGaoException(20001,"批量删除视频失败");
        }
        return null != count && count > 0;
    }

    @Override
    public List<EduCourse> getByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id",teacherId);
        // 按照最后更新时间降序
        wrapper.orderByDesc("gmt_modified");
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    @Override
    public Map<String, Object> getPageList(Page<EduCourse> pageCourse,CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageCourse, queryWrapper);

        List<EduCourse> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();
        boolean hasNext = pageCourse.hasNext();
        boolean hasPrevious = pageCourse.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    // 根据课程id获取课程web信息
    @Override
    public CourseWebVo selectInfoWebById(String id) {
        CourseWebVo courseWebVo = baseMapper.selectInfoWebById(id);
        return courseWebVo;
    }

    // 根据课程id修改浏览数
    @Override
    public void updatePageViewCount(String id) {
        EduCourse eduCourse = baseMapper.selectById(id);
        eduCourse.setViewCount(eduCourse.getViewCount()+ 1);
        baseMapper.updateById(eduCourse);
    }

}
